/**
 * 工具型代码 提供各种重用function
 */
define( [
  'require',
  'jquery',
  './editData',
  './dataHandle',
  '../modules/createEditor',
  'bigwe_utils',
  'artCategory',
  'api',
  'selector',
  'message',
  'constants',
  'artTemplate',
  'bigwe_component'
], function( require, $, editData, dh, editorObj, bu, ac, api ) {

  var ShowTitleMessage = require( 'message' );
  var c = require( 'constants' );
  var at = require( 'artTemplate' );
  var components = require( 'bigwe_component' );
  var showTime = ShowTitleMessage.showTime;

  var category = ac.CATEGORY_NAME;
  var returnParam = {
    options: {
      graphDataLength: 0, // 用于新建图文时的key设置
      isEditSet: 0
    },
    // 将参数中的所有文章属性全部填充到页面里 如值为空将重置到默认状态
    htmlLoadIn: function( json ) {
      var $this = this;

      function imgUrlCheck( url ) {
        var _regex = /^((http|https):\/\/img03\.store\.sogou\.com)(.+)/;
        return _regex.test( url );
      }
      var $editColumn2 = $( '.edit-column>.edit-column2' );
      var json = json || dh.articleBean();
      // 标题
      $( '.article-title-input>.edit-input', $editColumn2 ).val( json.title ).trigger( 'change' );
      // 作者
      $( '.article-author-input>.edit-input', $editColumn2 ).val( json.author ).trigger( 'change' );
      // 主要内容
      editorObj.setContent( json.content || json.content_noencode || '' );
      $( editorObj.body ).mediaSrcAttr();
      //editorObj.execCommand('inserthtml', imgsrcAttr(json.content));

      function setchecked() {
        $( '.input-srcurl>input[type="text"]' ).val( json.source_url );
        $( '.srcurl-formwork>.srcurl>input', $editColumn2 ).prop( 'checked', 'checked' ).trigger( 'change' );
      }
      // 原文链接	
      if ( json.source_url ) {
        setchecked();
      } else {
        if ( !json.isSource_url ) {
          $( '.input-srcurl>input[type="text"]' ).val( '' );
          $( '.srcurl-formwork>.srcurl>input', $editColumn2 ).removeAttr( 'checked' ).trigger( 'change' );
        } else {
          setchecked();
        }
      }
      // 封面图片
      var defaultCoverUrl = '/images/wuyulantu';
      if ( defaultCoverUrl.indexOf( json.cdn_url ) > -1 ) {
        $( '.cover-controll>.reset-mark', $editColumn2 ).val( '' ).trigger( 'change' );
      } else {
        $( '.cover-controll>.reset-mark', $editColumn2 ).val( bu.wechartImgCheck( json.cdn_url ) ).trigger( 'change' );
      }
      // 封面图片是否显示在正文
      if ( json.show_cover_pic === '1' ) {
        $( '.show-cover', '.article-edit-details' ).prop( 'checked', 'checked' ).trigger( 'change' );
      } else {
        $( '.show-cover', '.article-edit-details' ).removeAttr( 'checked' ).trigger( 'change' );
      }
      // 摘要
      if ( json.desc ) {
        $( '#txt_model' ).val( ( json.desc || '' ).substr( 0, 120 ) ).trigger( 'change' );
      } else {
        $( '#txt_model' ).val( '' ).trigger( 'change' );
      }
      // 原创
      if ( json.declare_original == 1 || json.declare_original == 2 ) {
        this.originalSet( json );
      } else {
        this.originalCancel();
      }
      // 文章分类
      var noCategory = '请选择一个分类';
      var noGroup = '未分组';
      if ( json.article_field ) {
        $( "#cate-text-div" ).text( category[ json.article_field ] || noCategory );
      } else {
        $( "#cate-text-div" ).text( noCategory );
      }
      // 自定义分组
      if ( json.article_category ) {
        $( "#cateDiy-text-div" ).text( json.article_category_name || noGroup );
        // 此处因为修改分组数据为延迟加载 所以不起作用
        $( '#category-diy-select>[value="' + json.article_category + '"]', '#category-update' ).attr( 'selected', 'selected' ).parent().selectpicker( 'refresh' );
      } else {
        $( "#cateDiy-text-div" ).text( noGroup );
        $( '#category-diy-select>option' ).removeAttr( 'selected' ).parent().selectpicker( 'refresh' );
      }
      // 文章标签
      this.tageCreate( json.article_label );
      // 设置编辑器可编辑区域paddingtop
      //$('.title-input', '.title-author-div').trigger('keyup');
      if ( !this.options.isEditSet ) {
        for ( var i in editData.graphDataDetails ) {
          editData.graphDataDetails[ i ].isEdit = 0;
        }
        this.options.isEditSet = !0;
      }
      // 默认模板开关
      $( '.defualt_template .temple_list input[type="checkbox"]' ).removeAttr( 'checked' );
      if ( !json.gzhstyle || !json.gzhstyle.length ) {
        $( '.defualt_template [bw-ui-switch]' ).removeClass( 'active' ).trigger( 'change' );
      } else {
        for ( i in json.gzhstyle ) {
          $( '.defualt_template .temple_list input[type="checkbox"][value="' + json.gzhstyle[ i ] + '"]' ).prop( 'checked', 'checked' );
        }
        $( '.defualt_template [bw-ui-switch]' ).addClass( 'active' ).trigger( 'change' );
      }
    },
    // 设置原创信息的状态
    originalSet: function( jsonObj ) {
      var reprintString = {
        '1': '允许转载',
        '0': '禁止转载'
      }
      var $originalDiv = $( '.original-div' );
      if ( jsonObj.declare_original == 1 || jsonObj.declare_original == 2 ) {
        var categoryName = category[ jsonObj.article_field ] || '未分类';
        $( "#platf-name", $originalDiv ).text( jsonObj.platfName || '' );
        $( "#author-name", $originalDiv ).text( jsonObj.authorName || '' );
        $( "#article-category", $originalDiv ).text( categoryName );
        $( "#original-setting", $originalDiv ).text( reprintString[ jsonObj.reprintSet ] || reprintString[ '1' ] );
        $( '.original-div-msg', $originalDiv ).text( '已声明原创：' );
        $( "#btn-declar-original, .original-div-con>.msg1", $originalDiv ).hide();
        $( '.original-div-title>.btn-a-blue, .original-div-con>.msg2', $originalDiv ).show();
        $( '.original-logo', $originalDiv ).show();
        // 设置数据
        editData.setAttrbute( jsonObj );
        // 设置弹出框的值
        this.originalModalSet( jsonObj );
        // 同时设置原创声明下面的领域名称
        $( '#cate-text-div' ).text( categoryName );
      } else {
        this.originalCancel();
      }
    },
    // 取消原创信息
    originalCancel: function() {
      var $originalDiv = $( '.original-div' );
      $( '.original-div-msg', $originalDiv ).text( '原创：未声明' );
      $( "#btn-declar-original, .original-div-con>.msg1", $originalDiv ).show();
      $( '.original-div-title>.btn-a-blue, .original-div-con>.msg2', $originalDiv ).hide();
      $( '.original-logo', $originalDiv ).hide();
      // 设置弹出框的值
      this.originalModalSet( dh.articleBean() );
      editData.setAttrbute( 'isAllCheck', 0 );
    },
    // 原创弹框设置
    originalModalSet: function( json ) {
      var $original = $( '#original' );
      $( '[name="bigweFirst"][value="' + ( json.bigweFirst || '1' ) + '"]' ).prop( 'checked', 'checked' ).trigger( 'change' );
      $( '#original-resourceUrl-ipt', $original ).val( json.resourceUrl || '' );
      if ( json.bigweFirst != '1' && $( '[name="bigweFirst"]:checked' ).val() === '0' ) {
        $( '#original-platf-ipt', $original ).val( json.platfName || '' );
      }
      $( '#original-author-ipt', $original ).val( json.authorName || '' );
      $( '#original-cate-spa>option[value="' + ( json.article_field || '' ) + '"]', $original ).attr( 'selected', 'selected' ).parent().selectpicker( 'refresh' );
      $( '[name="reprintSet"][value="' + ( json.reprintSet || '1' ) + '"]' ).prop( 'checked', 'checked' ).trigger( 'change' );
    },
    // 创建一个右侧的图文信息
    graphListCreate: function( obj, key ) {
      if ( $( ".graph-manage>.comb-list>li" ).length >= 8 ) {
        ShowTitleMessage.showWarning( "最多只能添加8篇文章哦！", showTime );
        editData.graphDataDetails.splice( 8, editData.graphDataDetails.length - 8 );
        return;
      }
      var graphData = {
        title: '',
        cdn_url: ''
      };
      graphData = $.extend( graphData, obj );

      function bgSet( obj ) {
        bu.prepImageRequest( bu.wechartImgCheck( graphData.cdn_url ), function( img ) {
          obj.css( 'background-image', 'url(' + img.src + ')' );
        } );
      }
      var liID = 'cover' + parseInt( Math.random() * 10000e3 );

      var $newGraph = $( at( 'graph_item_html', {
        liID: liID,
        editType: editData.editType
      } ) );
      $( '.title', $newGraph ).text( graphData.title );
      var graphDataLength = this.options.graphDataLength;
      if ( editData.editType == 1 ) {
        editData.graphDataDetails = [ obj ];
        $( '.graph-manage>.comb-list' ).html( $newGraph );
      } else {
        editData.graphDataDetails.push( obj );
        $( '.graph-manage>.comb-list' ).append( $newGraph );
      }

      $( '[data-toggle="tooltip"]', $newGraph ).tooltip( {
        container: 'body'
      } );

      if ( graphData.cdn_url ) bgSet( $( '.cover', '#' + liID ) );
      return $newGraph;
    },
    // 循环创建右侧图文信息
    graghListCreateJsons: function( jsonObj, isSetTimeout ) {
      if ( !jsonObj || jsonObj.length == 0 ) return;
      $( ".comb-list" ).empty();
      editData.graphDataDetails = [];
      for ( i in jsonObj ) {
        this.graphListCreate( jsonObj[ i ], i );
      }
      $( '[data-toggle="tooltip"]', '.comb-list' ).tooltip( {
        'container': 'body',
        'trigger': 'hover'
      } );
      $( ".comb-list>li:first-child .js_writing" ).trigger( 'click' );
      if ( editData.editType == 1 ) {
        this.htmlLoadIn( editData.graphDataDetails[ 0 ] );
      }
      if ( !editData.isCreate && isSetTimeout ) {
        this.changeFalseSet();
      }
      /*var setInterTimer = setInterval(function() {

      	if (editData.allIsReady === 2) {
      		clearInterval(setInterTimer);
      	}

      }, .5e3);*/
      return this;
    },
    // 创建标签
    tageAppend: function( tageName ) {
      $( '.tage-content .content', '.categoryAndTag-div' ).append( '<div title="' + tageName + '">' + tageName + '</div>' );
    },
    // 设置标签输入框的宽度
    inputwidthset: function() {
      var contentWidth = $( '.tage-content .content' ).outerWidth( true ) + 4;
      var outerHeight = $( '.tage-content .input-tage' ).outerWidth( true );
      $( '.tage-content .tag-input' ).width( outerHeight - contentWidth );
    },
    // 标签添加
    tageChange: function( tageName ) {
      var $contentDiv = $( '.tage-content .content', '.categoryAndTag-div' );
      var isRepeated = false;
      var tageStr = '';
      $( 'div', $contentDiv ).each( function() {
        var thisText = $( this ).text();
        if ( thisText === tageName ) {
          isRepeated = true;
          return false;
        }
      } );

      if ( isRepeated ) {
        ShowTitleMessage.showWarning( "已存在相同的标签", showTime );
        $( '.input-tage>input' ).val( '' );
        return;
      }

      if ( tageName ) {
        this.tageAppend( tageName );
        $( '.input-tage .tag-input' ).val( '' );
      }
      this.inputwidthset();
      var $tageContent = $( '.tage-content' );
      if ( $( '.content>div', $tageContent ).length >= 5 ) {
        $( '.input-tage .tag-input', $tageContent ).hide();
      } else {
        $( '.input-tage .tag-input', $tageContent ).show();
        if ( $( '.content>div', $tageContent ).length < 1 ) {
          //$('.input-tage>.spa_gray').show();
        }
      }
      editData.setAttrbute( "article_label", $( 'div', $contentDiv ).map( function() {
        return $( this ).text()
      } ).get().join( ',' ) );
    },
    // 循环创建已存在的标签
    tageCreate: function( tageNameArray ) {
      $( '.input-tage .tag-input', $tageContent ).show();
      if ( $.trim( tageNameArray ) ) {
        var $tageContent = $( '.tage-content' );
        tageArray = tageNameArray.split( ',' );
        if ( tageArray.length > 0 ) {
          $( '.input-tage .spa_gray', $tageContent ).hide();
        }
        if ( tageArray.length >= 5 ) {
          $( '.input-tage .tag-input', $tageContent ).hide();
        }
        $( '.tage-content .content', '.categoryAndTag-div' ).empty();
        for ( var i = 0; i < tageArray.length; i++ ) {
          if ( tageArray[ i ] ) {
            this.tageAppend( tageArray[ i ] );
          }
        }
        editData.setAttrbute( "article_label", tageNameArray );
      } else {
        $( '.tage-content .content', '.categoryAndTag-div' ).empty();
        editData.setAttrbute( "article_label", '' );
      }
      this.inputwidthset();
    },
    // 创建封面图片预览用html
    coverHtmlBuild: function() {
      var url = $( '.cover-input', '.article-edit-details' ).val();
      return '<p id="coverImg"><img width="100%" src="' + url + '" /></p>';
    },
    // 设置页面状态为已保存或未改变过的
    changeFalseSet: function() {
      setTimeout( function() {
        editData.isContentChange = false;
        editData.editModalReady = true;
      }, .1e3 );
    },
    // 抓取远程文章完成后的回调
    remotoHtmlCallback: function( data, url ) {

      function fullIn() {
        returnParam.htmlLoadIn( returnParam.remotoDataTrans( data, url ) );
      }

      if ( !this.getContent() ) {
        fullIn();
        return true;
      } else {
        components.confirm( function() {
          fullIn();
          return true;
        } );
      }

      return false;
    },
    remotoDataTrans: function( data, url ) {
      url = new URL( url );
      var trans = {
        'www.toutiao.com': function( data ) {
          var context = $( data ).find( '#article-main' );
          return {
            title: $( '.article-title', context ).text().trim(),
            author: $( '.articleInfo .src', context ).text().trim(),
            content: $( '.article-content', context ).html(),
            source_url: url.href,
            cdn_url: $( '.article-content img', context ).eq( 0 ).prop( 'src' )
          }
        },
        'www.yidianzixun.com': function( data ) {
          var context = $( data ).find( '.left-wrapper' );
          $( '.report', context ).remove();

          return {
            title: $( '>h2', context ).text() || $( '.content-hd-media h2', context ).text(),
            author: $( '>.meta .doc-source', context ).text(),
            content: $( '.content-bd', context ).html(),
            source_url: url.href,
            cdn_url: $( '.content-bd img', context ).eq( 0 ).prop( 'src' )
          };
        },
        'baijia.baidu.com': function( data ) {

          var context = $( data ).find( '.news-left' );
          $( '.rights,.read-like,.weixin-qrcode,.qrcode-text,.share', context ).remove();
          // var context = $( data ).find( '#page' );
          // $( '.l-main-inner-ad', context ).remove();

          return {
            title: $( 'h1.title', context ).text(),
            author: $( '.author > a', context ).text(),
            content: /*$( '>blockquote', context ).prop( 'outerHTML' ) + */ $( '.news-content', context ).html(),
            // article_label: $( '.article-info .tag', context ).map( function() {
            // 	return $( this ).text()
            // } ).get().join( ',' ),
            source_url: url.href,
            cdn_url: $( '.news-content img', context ).eq( 0 ).prop( 'src' )
          }
        },
        '163.com': function( data ) {
          var context = $( data ).find( '#epContentLeft' );
          $( '.gg200x300', context ).remove();
          $( '.ad_hover_href', context ).next().remove();

          return {
            title: $( '>h1', context ).text(),
            author: $( '#ne_article_source', context ).text(),
            content: $( '#endText', context ).html(),
            source_url: url.href,
            cdn_url: $( '#endText img', context ).eq( 0 ).prop( 'src' )
          };
        },
        'www.jianshu.com': function( data ) {
          var context = $( data ).find( '.article' );

          return {
            title: $( '>.title', context ).text(),
            author: $( '.author .info>.name', context ).text(),
            content: $( '.show-content', context ).html(),
            source_url: url.href,
            cdn_url: $( '.show-content img', context ).eq( 0 ).prop( 'src' )
          };
        },
        'mp.weixin.qq.com': function( data ) {
          return JSON.parse( data );
        }
      };
      var hostname = '';
      var currentHostName = url.hostname;
      if ( currentHostName.indexOf( 'baijia.baidu.com' ) > -1 ) {
        hostname = 'baijia.baidu.com';
      } else if ( currentHostName.indexOf( '163.com' ) > -1 ) {
        hostname = '163.com';
      } else {
        hostname = currentHostName;
      }

      return trans[ hostname ]( data );
    },
    // 插入一个图片到编辑器
    comInsertImage: function( image ) {
      var OPTIONS = {
        id: '',
        src: '',
        title: ''
      }
      $.extend( OPTIONS, image );
      var html = '<p><br/></p><img alt="' + OPTIONS.title + '" id="' + OPTIONS.id + '" src="' + OPTIONS.src + '"><p><br/></p>'
      this.execCommand( 'inserthtml', html );
    },
    // 根据文章id获取文章信息
    getArticleByIdAjax: function( articleID, callback ) {
      // 根据文章ID请求单片文章数据 
      return $.ajax( {
        type: 'get',
        url: '/edit_text/get_article_by_id',
        data: {
          'article_id': articleID,
          'done': 'forEditor'
        },
        success: function( data ) {
          data = $.parseJSON( data );
          if ( data.ret * 1 === 80234 ) {
            ShowTitleMessage.showWarning( '文章不能选择，作者设置为禁止转载！' );
            return;
          }
          if ( callback ) {
            callback.apply( this, arguments );
          }
        },
        error: function() {
          ShowTitleMessage.showWarning( '发生未知错误！', showTime );
        },
        complete: function() {
          //ShowTitleMessage.hide();
        }
      } );
    },
    // 用户领域和分组请求
    usersGroupArrayRequest: function( fn ) {
      var $this = this;
      if ( $this.usersGroupArray ) {
        fn( $this.usersGroupArray );
      } else {
        $.get( api.EDIT_TEXT.GET_CATEGORY, {}, function( data ) {
          $this.usersGroupArray = $.parseJSON( data );
          fn( $this.usersGroupArray );
        } );
      }
    },
    timthumbFormat: function( str, w, h ) {
      if ( bu.parseURL( str ).host.indexOf( 'bigwe.com' ) < 0 ) {
        return c.surpportHostName + '/timthumb.php?' + 'src=' + str + ( w ? ( '&w=' + w ) : w ) + ( h ? ( '&h=' + h ) : '' );
      }
      return str;
    },
  }

  return returnParam;
} );